﻿import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'non_gps_exercise_recording_state.dart';
import '../../../../common/model/exercise_type.dart';

/// 非GPS运动记录控制器
class NonGpsExerciseRecordingLogic extends GetxController {
  final NonGpsExerciseRecordingState state = NonGpsExerciseRecordingState();
  
  Timer? _timer;
  ExerciseType? exerciseType;

  @override
  void onInit() {
    super.onInit();
    
    // 获取传入的运动类型参数
    final arguments = Get.arguments as Map<String, dynamic>?;
    if (arguments != null) {
      exerciseType = arguments['exerciseType'] as ExerciseType?;
      
      // 设置目标信息
      if (arguments['targetTime'] != null) {
        state.targetInfo.value = arguments['targetTime'].toString();
        state.targetTime.value = arguments['targetTime'].toString();
      }
      if (arguments['targetCalories'] != null) {
        state.targetCalories.value = arguments['targetCalories'].toString();
        if (state.targetInfo.value.isEmpty) {
          state.targetInfo.value = '${arguments['targetCalories']}千卡';
        }
      }
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  /// 开始运动
  void startExercise() {
    state.isRecording.value = true;
    state.isPaused.value = false;
    state.duration.value = 0;
    state.calories.value = 0;
    state.steps.value = 0;
    
    // 启动计时器
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!state.isPaused.value) {
        state.duration.value++;
        
        // 模拟卡路里和步数增长
        if (exerciseType != null) {
          final caloriesPerSecond = exerciseType!.caloriesPerMinute / 60;
          state.calories.value = (state.duration.value * caloriesPerSecond).round();
          
          // 模拟步数（假设每分钟120步）
          state.steps.value = (state.duration.value * 2).round();
        }
        
        // 检查是否达到目标
        _checkTargetReached();
      }
    });
    
    Toast.show('${exerciseType?.name ?? '运动'}已开始');
  }

  /// 暂停运动
  void pauseExercise() {
    state.isPaused.value = true;
    Toast.show('运动已暂停');
  }

  /// 继续运动
  void resumeExercise() {
    state.isPaused.value = false;
    Toast.show('运动已继续');
  }

  /// 结束运动
  void endExercise() {
    state.isRecording.value = false;
    state.isPaused.value = false;
    _timer?.cancel();
    
    Toast.show('运动已结束，时长: ${_formatDuration(state.duration.value)}');
  }

  /// 锁定屏幕
  void lockScreen() {
    Toast.show('屏幕已锁定');
  }

  /// 切换记录状态（保留兼容性）
  void toggleRecording() {
    if (state.isRecording.value) {
      if (state.isPaused.value) {
        resumeExercise();
      } else {
        pauseExercise();
      }
    } else {
      startExercise();
    }
  }

  /// 获取当前时间
  String getCurrentTime() {
    final now = DateTime.now();
    return '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
  }

  /// 检查是否达到目标
  void _checkTargetReached() {
    // 检查时间目标
    if (state.targetTime.value.isNotEmpty) {
      final targetMinutes = _parseTimeToMinutes(state.targetTime.value);
      if (state.duration.value >= targetMinutes * 60) {
        _showTargetReachedDialog('时间目标');
        return;
      }
    }
    
    // 检查卡路里目标
    if (state.targetCalories.value.isNotEmpty) {
      final targetCalories = int.tryParse(state.targetCalories.value) ?? 0;
      if (state.calories.value >= targetCalories) {
        _showTargetReachedDialog('卡路里目标');
        return;
      }
    }
  }

  /// 显示目标达成对话框
  void _showTargetReachedDialog(String targetType) {
    endExercise();
    
    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Text(
          '目标达成！',
          style: TextStyle(color: Colors.white, fontSize: 18.sp),
        ),
        content: Text(
          '恭喜您完成了$targetType！\n运动时长: ${_formatDuration(state.duration.value)}\n消耗卡路里: ${state.calories.value}千卡\n步数: ${state.steps.value}步',
          style: TextStyle(color: Colors.white, fontSize: 14.sp),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text(
              '确定',
              style: TextStyle(color: Colors.orange),
            ),
          ),
        ],
      ),
    );
  }

  /// 解析时间字符串为分钟数
  int _parseTimeToMinutes(String timeStr) {
    try {
      final parts = timeStr.split(':');
      if (parts.length == 2) {
        final hours = int.parse(parts[0]);
        final minutes = int.parse(parts[1]);
        return hours * 60 + minutes;
      }
    } catch (e) {
      // 解析失败，返回默认值
    }
    return 20; // 默认20分钟
  }

  /// 格式化时长显示
  String _formatDuration(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;
    
    if (hours > 0) {
      return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
    } else {
      return '${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
    }
  }
}
